package com.itheima.webserver.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.commons.model.domain.User;
import com.itheima.commons.model.domain.UserFreeze;
import com.itheima.commons.model.domain.UserInfo;
import com.itheima.commons.model.mongo.*;
import com.itheima.commons.model.vo.*;
import com.itheima.dubbo.interfaces.*;
import com.itheima.commons.model.domain.UserStatus;
import com.itheima.commons.model.vo.ManageVo;
import com.itheima.commons.model.vo.PageResult;
import com.itheima.commons.model.vo.UserProfileVo;
import com.itheima.commons.model.mongo.Message;
import com.itheima.commons.model.mongo.Publish;
import com.itheima.commons.model.vo.MessageVo;
import com.itheima.commons.model.vo.Totals;
import com.itheima.dubbo.interfaces.PublishApi;
import com.itheima.dubbo.interfaces.UserInfoApi;
import com.itheima.dubbo.interfaces.ManageApi;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;


import java.util.*;

/**
 * @Auther: alongchan
 * @Date: 2021/12/18 18:39
 * @Description:
 */
@Service
public class ManageService {
    @Reference
    private UserApi userApi;

    @Reference
    private UserFreezeApi userFreezeApi;

    @Reference
    private ManageApi manageApi;
    @Reference
    private PublishApi publishApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private CommentApi commentApi;
    @Reference
    private VideoApi videoApi;
    @Reference
    private LogApi logApi;

    @Reference
    private UserLikeApi userLikeApi;

    @Reference
    private RecommendUserApi recommendUserApi;


    //用户个人资料展示
    public UserProfileVo queryUserProfile(String userId) {
        //查询user对象
        User user = userApi.queryUserById(Convert.toLong(userId));
        //查询userInfo对象
        UserInfo userInfo = userInfoApi.findUserInfoByUserId(Convert.toLong(userId));
        //查询userStatus对象
        UserStatus userStatus = userInfoApi.queryUserStatusByUid(Convert.toLong(userId));
        //拼接userProfileVo对象
        UserProfileVo userProfileVo = new UserProfileVo();
        userProfileVo.setId(user.getId());
        userProfileVo.setNickname(userInfo.getNickName());
        userProfileVo.setMobile(user.getMobile());
        userProfileVo.setSex(userInfo.getSex() == 1 ? "男" : "女");
        userProfileVo.setPersonalSignature(userStatus.getPersonalSignature());
        userProfileVo.setAge(userInfo.getAge().toString());
        userProfileVo.setIncome(userInfo.getIncome());
        userProfileVo.setOccupation(userInfo.getIndustry());
        userProfileVo.setUserStatus(userStatus.getUserStatus());
        userProfileVo.setCreated(userInfo.getCreated().toString());
        userProfileVo.setCity(userStatus.getLastLoginLocation());
        userProfileVo.setLastActiveTime(userStatus.getLastActiveTime().toString());
        userProfileVo.setLastLoginLocation(userStatus.getLastLoginLocation());
        userProfileVo.setLogo(userInfo.getLogo());
        userProfileVo.setTags(userInfo.getTags());

        //查询喜欢的人数
        Long likeCount = userLikeApi.queryLikeCount(Convert.toLong(userId));
        //查询喜欢该用户的人数
        Long fanCount = userLikeApi.queryFanCount(Convert.toLong(userId));
        //查询推荐的人数
        Long matchCount = recommendUserApi.queryMatchUserCount(Convert.toLong(userId));
        userProfileVo.setCountBeLiked(likeCount.toString());
        userProfileVo.setCountLiked(fanCount.toString());
        userProfileVo.setCountMatching(matchCount.toString());


        return userProfileVo;
    }

    //用户数据翻页
    public PageResult userDataPageTurning(Integer page, Integer pagesize, String userId, String nickname, String city) {
        //根据条件先查寻出符合条件的userInfo对象

        List<UserInfo> userInfoList = new ArrayList<>();
        if (StrUtil.isNotBlank(userId)) {
            UserInfo userInfo = userInfoApi.findUserInfoByUserId(Convert.toLong(userId));
            userInfoList.add(userInfo);
        }else {
            userInfoList = userInfoApi.queryAllUserInfoMatchFields(page, pagesize, nickname, city);
        }
        //根据userInfo对象获取uid集合
        List<Long> userIds = CollUtil.getFieldValues(userInfoList, "userId", Long.class);
        //根据userIds查询user集合
        List<User> userList = userApi.queryUserListByIds(userIds);
        //根据userIds集合去查询符合条件的userStatus集合
        List<UserStatus> userStatusList = userInfoApi.queryAllUserStatusMatchFields(userIds);
        List<ManageVo> manageVoList = new ArrayList<>();
        for (User user : userList) {
            for (UserInfo userInfo : userInfoList) {
                for (UserStatus userStatus : userStatusList) {
                    if (user.getId().equals(userInfo.getUserId()) && user.getId().equals(userStatus.getUserId())) {
                        ManageVo manageVo = new ManageVo();
                        manageVo.setId(userInfo.getUserId());
                        manageVo.setLogo(userInfo.getLogo());
                        manageVo.setLogoStatus(userStatus.getLogoStatus());
                        manageVo.setNickname(userInfo.getNickName());
                        manageVo.setMobile(user.getMobile());
                        manageVo.setSex(userInfo.getSex().toString());
                        manageVo.setAge(userInfo.getAge().toString());
                        manageVo.setOccupation(userInfo.getIndustry());
                        manageVo.setUserStatus(userStatus.getUserStatus());
                        manageVo.setLastActiveTime(userStatus.getUserStatus());
                        manageVo.setCity(userInfo.getCity());
                        manageVoList.add(manageVo);
                    }
                }
            }
        }

        //拼接vo对象集合返回给前端
        return new PageResult(page, pagesize, Convert.toLong(manageVoList.size()), manageVoList);
    }

    //用户冻结操作
    public String userFreezeOperation(String userId, String freezingTime, String freezingRange, String reasonsForFreezing, String frozenRemarks) {
        //先查询冻结表里是否有该用户的冻结信息
        UserFreeze freeze = userFreezeApi.queryUserFreezeInfo(Convert.toLong(userId));
        //如果有就执行更新操作
        if (ObjectUtil.isNotEmpty(freeze)) {
            userFreezeApi.updateUserFreezeInfo(Convert.toLong(userId),freezingTime,freezingRange,reasonsForFreezing,frozenRemarks);
        }else {
            //如果没有就执行新增
            userFreezeApi.insertUserFreezeInfo(Convert.toLong(userId),freezingTime,freezingRange,reasonsForFreezing,frozenRemarks);
        }
        //更新userStatus里面的用户冻结信息
        String userStatus = "2";
        userInfoApi.updateUserStatusByUserId(Convert.toLong(userId),userStatus);
        return "操作成功";
    }

    //用户解冻操作
    public String userUnfreezing(String userId, String reasonsForThawing) {
        //直接解冻
        userFreezeApi.unFreezeUser(Convert.toLong(userId),reasonsForThawing);
        //更改userStatus里面的用户冻结信息
        String userStatus = "1";
        userInfoApi.updateUserStatusByUserId(Convert.toLong(userId),userStatus);
        return "操作成功";
    }




    //获取所有动态
    public PageResult getAllMessages(Map<String, String> params) {
        //从前台传递的数据中获取参数
        String pagesize = params.get("pagesize");
        Integer pageSize = Convert.toInt(pagesize);

        String page1 = params.get("page");
        Integer page = Convert.toInt(page1);

        String sd = params.get("sd");
        String ed = params.get("ed");
        String id = params.get("id");
        Long userId = Convert.toLong(id);

        //开始时间
        Long startTime = Convert.toLong(sd);
        //结束时间
        Long endTime = Convert.toLong(ed);

        /*params.get("")*/



        String state = params.get("state");
        String sortProp = params.get("sortProp");
        String sortOrder = params.get("sortOrder");
        List<Message> messages = new ArrayList<>();
        if (state.equals("2")) {
            //查询全部message
            messages = manageApi.getAll(page, pageSize, userId, state, sortProp, sortOrder,startTime,endTime);
        }else if(state.equals("5")){
            //查询已通过的动态，包括机器通过和人工审核通过
            messages = manageApi.getPassedMessagesByState(page, pageSize, userId, state, sortProp, sortOrder,startTime,endTime);
        } else {
            //根据指定的参数获取动态
            messages = manageApi.getAllMessagesByState(page, pageSize, userId, state, sortProp, sortOrder,startTime,endTime);
        }
        //拼凑vo对象
        List<MessageVo> messageVos = new ArrayList<>();
        for (Message message : messages) {
            ObjectId publishId = message.getPublishId();
            Publish publish = publishApi.queryPublishById(publishId.toHexString());
            UserInfo userInfo = userInfoApi.findUserInfoByUserId(message.getUserId());
            MessageVo messageVo = new MessageVo();
            messageVo.setId(publishId.toHexString());
            messageVo.setNickname(userInfo.getNickName());
            messageVo.setUserId(Convert.toInt(message.getUserId()));
            messageVo.setUserLogo(userInfo.getLogo());
            messageVo.setCreateDate(Convert.toInt(publish.getCreated()));
            messageVo.setText(publish.getText());
            messageVo.setState(message.getState());
            messageVo.setReportCount(message.getReportCount());
            Long likeCount = commentApi.queryCommentCount(publishId.toHexString(), 2);
            Long commentCount = commentApi.queryCommentCount(publishId.toHexString(), 3);
            messageVo.setLikeCount(Convert.toInt(likeCount));
            messageVo.setCommentCount(Convert.toInt(commentCount));
            messageVo.setForwardingCount(0);
            messageVo.setMedias(publish.getMedias().toArray(new String[0]));
            messageVos.add(messageVo);
        }
        //全部通过数量
        Integer totalCount = manageApi.findTotalCount(userId, startTime, endTime);
        //待审核数量
        Integer waitCheckCount = manageApi.findWaitCheckCount(userId, startTime, endTime);
        //通过数量
        Integer passCount = manageApi.findPassCount(userId, startTime, endTime);
        //已拒绝数量
        Integer rejectCount = manageApi.findRejectCount(userId, startTime, endTime);
        List<Totals> totalsList = new ArrayList<>();
        totalsList.add(new Totals("全部", "2", totalCount));
        totalsList.add(new Totals("待审核", "3", waitCheckCount));//待人工审核
        totalsList.add(new Totals("已通过", "5", passCount));//人工和机器审核通过
        totalsList.add(new Totals("已拒绝", "4", rejectCount));//人工审核拒绝
        Long count = Convert.toLong(totalCount);
        switch (state) {
            case "3": {
                count = Convert.toLong(waitCheckCount);
                break;
            }
            case "5": {
                count = Convert.toLong(passCount);
                break;
            }
            case "4": {
                count = Convert.toLong(rejectCount);
                break;
            }
        }
        PageResult pageResult = new PageResult(count, pageSize, Convert.toLong((count / pageSize) <= 1 ? 1 : (count / pageSize)), page, messageVos, totalsList);
        return pageResult;
    }

    //审核通过
    public Map<String, String> passMessage(List<String> ids) {
        HashMap<String, String> map = new HashMap<>();
        boolean flag = true;
        for (String id : ids) {
            if (!manageApi.passMessage(id)) {
                //如果审核通过,将这条动态存入到publish表中
                Publish publish = publishApi.queryPublishById(id);
                publishApi.publish(publish);



                flag = false;
            }
        }
        if (flag) {
            map.put("message", "审核成功,已通过");
        } else {
            map.put("message", "审核失败");
        }
        return map;
    }

    //审核拒绝
    public Map<String, String> rejectMessage(List<String> ids) {
        HashMap<String, String> map = new HashMap<>();
        boolean flag = true;
        for (String id : ids) {
            if (!manageApi.rejectMessage(id)) {
                flag = false;
            }
        }
        if (flag) {
            map.put("message", "审核成功,已通过");
        } else {
            map.put("message", "审核失败");
        }
        return map;
    }

    //消息审核撤销
    public Map<String, String> revocationMessage(List<String> ids) {
        HashMap<String, String> map = new HashMap<>();
        boolean flag = true;
        for (String id : ids) {
            if (!manageApi.revocationMessage(id)) {
                flag = false;
            }
        }
        if (flag) {
            map.put("message", "审核成功,已通过");
        } else {
            map.put("message", "审核失败");
        }
        return map;

    }

    //查询视频记录
    public PageResult getUserVideoRecord(Map<String, String> params) {
        String page = params.get("page");
        String pageSize = params.get("pagesize");
        String uid = params.get("uid");
        List<Video> videos = videoApi.findUserVideoRecord(Convert.toInt(page), Convert.toInt(pageSize), Convert.toLong(uid));
        List<VideoRecordVo> videoRecordVos = new ArrayList<>();
        for (Video video : videos) {
            VideoRecordVo videoRecordVo = new VideoRecordVo();
            UserInfo userInfo = userInfoApi.findUserInfoByUserId(video.getUserId());
            videoRecordVo.setId(video.getId().toHexString());
            videoRecordVo.setNickname(userInfo.getNickName());
            videoRecordVo.setUserId(video.getUserId());
            videoRecordVo.setCreateDate(Convert.toInt(video.getCreated()));
            videoRecordVo.setVideoUrl(video.getVideoUrl());
            videoRecordVo.setPicUrl(video.getPicUrl());
            videoRecordVo.setReportCount(0);
            videoRecordVo.setLikeCount(Convert.toInt(commentApi.queryCommentCount(video.getId().toHexString(), 1)));
            videoRecordVo.setCommentCount(Convert.toInt(commentApi.queryCommentCount(video.getId().toHexString(), 2)));
            videoRecordVo.setForwardingCount(0);
            videoRecordVos.add(videoRecordVo);
        }
        return new PageResult(Convert.toInt(page), Convert.toInt(pageSize), videoApi.findVideoCount(Convert.toLong(uid)), videoRecordVos);
    }

    //查询用户动态记录数
    public PageResult getUserMovementsRecord(Map<String, String> params) {
        String page = params.get("page");
        String pageSize = params.get("pagesize");
        String uid = params.get("uid");
        List<Message> messages = manageApi.findUserMovementsRecord(Convert.toInt(page), Convert.toInt(pageSize), Convert.toLong(uid));
        List<MessageVo> messageVos = new ArrayList<>();
        for (Message message : messages) {
            Publish publish = publishApi.queryPublishById(message.getPublishId().toHexString());
            UserInfo userInfo = userInfoApi.findUserInfoByUserId(publish.getUserId());
            MessageVo messageVo = new MessageVo();
            messageVo.setId(publish.getId().toHexString());
            messageVo.setNickname(userInfo.getNickName());
            messageVo.setUserId(Convert.toInt(publish.getUserId()));
            messageVo.setUserLogo(userInfo.getLogo());
            messageVo.setCreateDate(Convert.toInt(userInfo.getCreated()));
            messageVo.setText(publish.getText());
            messageVo.setState(manageApi.findMessageStateByPublishId(publish.getId()));
            messageVo.setReportCount(0);
            messageVo.setLikeCount(Convert.toInt(commentApi.queryCommentCount(publish.getId().toHexString(), 1)));
            messageVo.setCommentCount(Convert.toInt(commentApi.queryCommentCount(publish.getId().toHexString(), 2)));
            messageVo.setForwardingCount(0);
            messageVo.setMedias(publish.getMedias().toArray(new String[0]));
            messageVos.add(messageVo);
        }


        return new PageResult(Convert.toInt(page), Convert.toInt(pageSize), publishApi.findPublishCount(Convert.toLong(uid)), messageVos);

    }

    //查询消息详情
    public MessageVo getUserMessageDetail(String publishId) {
        Publish publish = publishApi.queryPublishById(publishId);
        ArrayList<Long> list = new ArrayList<>();
        list.add(1L);
        publish.setNotSeeList(list);
        publish.setSeeList(list);
        UserInfo userInfo = userInfoApi.findUserInfoByUserId(publish.getUserId());
        MessageVo messageVo = new MessageVo();
        messageVo.setId(publish.getId().toHexString());
        messageVo.setNickname(userInfo.getNickName());
        messageVo.setUserId(Convert.toInt(publish.getUserId()));
        messageVo.setUserLogo(userInfo.getLogo());
        messageVo.setCreateDate(Convert.toInt(publish.getCreated()));
        messageVo.setText(publish.getText());
        messageVo.setState(manageApi.findMessageStateByPublishId(new ObjectId(publishId)));
        messageVo.setReportCount(0);
        messageVo.setLikeCount(Convert.toInt(commentApi.queryCommentCount(publishId, 1)));
        messageVo.setCommentCount(Convert.toInt(commentApi.queryCommentCount(publishId, 2)));
        messageVo.setForwardingCount(0);
        messageVo.setMedias(publish.getMedias().toArray(new String[0]));
        messageVo.setTopState(manageApi.findMessageTopState(publishId));
        return messageVo;
    }

    //消息置顶
    public String messageTop(String publishId) {
        Boolean result = manageApi.modifyMessageTop(new ObjectId(publishId));
        if (result) {
            return "修改成功";
        } else {
            return "修改失败";
        }
    }

    //消息取消置顶
    public String messageUntop(String publishId) {
        Boolean result = manageApi.modifyMessageUntop(new ObjectId(publishId));
        if (result) {
            return "修改成功";
        } else {
            return "修改失败";
        }
    }

    //获取该条动态的所有评论
    public PageResult getAllComments(Map<String, String> params) {
        String publishId = params.get("messageID");
        String page = params.get("page");
        String pageSize = params.get("pagesize");
        List<Comment> comments = commentApi.findPublishCommentList(new ObjectId(publishId), Convert.toInt(page), Convert.toInt(pageSize));
        List<CommentManageVo> commentManageVos = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo info = userInfoApi.findUserInfoByUserId(comment.getUserId());
            CommentManageVo vo = new CommentManageVo();
            vo.setId(comment.getId().toHexString());
            vo.setNickname(info.getNickName());
            vo.setUserId(Convert.toInt(comment.getUserId()));
            vo.setContent(comment.getContent());
            vo.setCreateDate(DateUtil.date(comment.getCreated()).toString("yyyy-MM-dd HH:mm"));
            commentManageVos.add(vo);
        }
        return new PageResult(Convert.toInt(page), Convert.toInt(pageSize), Convert.toLong(comments.size()), commentManageVos);
    }

    //查询日志列表
    public PageResult getLogs(Map<String, String> params) {
        String page = params.get("page");
        String pageSize = params.get("pagesize");
        String uid = params.get("uid");
        List<Log> logs = logApi.findUserLogRecord(Convert.toInt(page), Convert.toInt(pageSize), Convert.toLong(uid));
        return new PageResult(Convert.toInt(page), Convert.toInt(pageSize), Convert.toLong(logs.size()), logs);
    }
}
